package base;

import java.util.List;
import java.util.Map;

import base.LoadingPager.LoadResult;
import utils.UIUtils;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;

/**
 * Fragment的基类
 * @author Anson-pc
 *
 */
public abstract class BaseFragment extends Fragment {

	private LoadingPager loadingpager;
	public LoadingPager getLoadingpager() {
		return loadingpager;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (loadingpager ==  null) {
			//创建LoadingPager
			loadingpager = new LoadingPager(UIUtils.getContext()){
				/**
				 * 正在在子线程中加载数据
				 */
				@Override
				protected LoadResult initData() {
					// TODO Auto-generated method stub
					return BaseFragment.this.initData();
				}

				@Override
				protected View initSuccessView() {
					// TODO Auto-generated method stub
					return BaseFragment.this.initSuccessView();
				}
				
			};
		}else{
			//当loadingPager已经创建了的时候
			ViewParent viewParent = loadingpager.getParent();
			if (viewParent != null && viewParent instanceof ViewGroup) {
				((ViewGroup)viewParent).removeView(loadingpager);
			}
			
		}
		return loadingpager;
	}

	protected abstract LoadResult initData();
	
	/**
	 * 创建成功的加载视图，触发加载数据
	 * 数据加载完成，得到数据加载结果，会重新刷新UI,而且数据加载成功并且视图还没有创建的时候会执行此方法
	 * @return
	 */
	protected abstract View initSuccessView();
	
	/**
	 * 请求回来的数据
	 * @return 不同LoadResult的状态值
	 */
	public LoadResult checkState(Object result){
		if (result ==null) {
			//返回空
			return LoadResult.EMPTY;
		}
		
		if (result instanceof List ) {
			if (((List) result).size() == 0) {
				return LoadResult.EMPTY;
			}
		}

		if (result instanceof Map ) {
			if (((Map) result).size() == 0) {
				return LoadResult.EMPTY;
			}
		}
		
		return LoadResult.SUCCESS;
		
	}

}
